﻿using System;
using System.Collections.Generic;
using System.Text;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Display;

namespace GISCommon.Business
{
    public class MeasureToolsHelper3
    {
        private AxMapControl _mapCtrl=null;
        private IPointCollection _pointClt = null;
        private bool _isStarted = false;
        private IPolyline _tempLine = null;
        private double _totalDistance = 0;
        private double _tempDistance = 0;
        private object _lineSymbol = null;
        private bool _canMoveRefresh = true;

        #region 对外函数

        /// <summary>
        /// 描述：调用前的初始化
        /// </summary>
        /// <param name="vMapControl">地图控件</param>
        public void Initial(AxMapControl vMapControl)
        {
            try
            {
                _mapCtrl = vMapControl;
                _mapCtrl.OnDoubleClick += new IMapControlEvents2_Ax_OnDoubleClickEventHandler(mapCtrl_OnDoubleClick);
                _mapCtrl.OnMouseUp += new IMapControlEvents2_Ax_OnMouseUpEventHandler(mapCtrl_OnMouseUp);
                _mapCtrl.OnMouseMove += new IMapControlEvents2_Ax_OnMouseMoveEventHandler(mapCtrl_OnMouseMove);
                _mapCtrl.OnAfterScreenDraw += new IMapControlEvents2_Ax_OnAfterScreenDrawEventHandler(_mapCtrl_OnAfterScreenDraw);
                _pointClt = new PolylineClass();
            }
            catch (Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用出错", ex);
            }
        }

        void _mapCtrl_OnAfterScreenDraw(object sender, IMapControlEvents2_OnAfterScreenDrawEvent e)
        {
            try
            {
                
                Draw();
            }
            catch (Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用出错", ex);
            }
        }

        void Draw()
        {
            try
            {
                if (_isStarted)
                {
                    //画线
                    IPolyline polyline = _pointClt as IPolyline;
                    if (polyline != null)
                    {
                        GISCommon.Tools.Drawing.DrawPolyline(_mapCtrl,
                            polyline, 0, 0, 255, 2);
                        //_mapCtrl.DrawShape(polyline,ref _lineSymbol);
                    }
                    IPoint pt = null;

                    //画临时线
                    if (_tempLine != null && _mapCtrl.CurrentTool == null)
                    {
                        if (_lineSymbol == null)
                        {
                            CreateLineSymbol();
                        }
                        pt = _tempLine.ToPoint;
                        //_mapCtrl.DrawShape(_tempLine,ref _lineSymbol);
                        GISCommon.Tools.Drawing.DrawPolyline(_mapCtrl,
                            _tempLine, 0, 0, 255, 2);
                    }

                    if (_mapCtrl.CurrentTool != null)
                    {
                        _canMoveRefresh = false;
                    }
                    else
                    {
                        _canMoveRefresh = true;
                    }

                    //画距离                    
                    string txt = "当前距离" + _tempDistance.ToString("#,###") + "米";
                    if (pt == null)
                    {
                        pt = _pointClt.get_Point(_pointClt.PointCount - 1);                        
                    }
                    DrawText(pt, txt);
                }
            }
            catch (Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用_mapCtrl_OnAfterScreenDraw出错", ex);
            }
        }

        private void CreateLineSymbol()
        {
            ISimpleLineSymbol lineSymbol =
                new ESRI.ArcGIS.Display.SimpleLineSymbolClass();
            ESRI.ArcGIS.Display.IRgbColor rgbColor =
                new ESRI.ArcGIS.Display.RgbColorClass();
            rgbColor.Red = 0;
            rgbColor.Green = 0;
            rgbColor.Blue = 255;
            lineSymbol.Color = rgbColor;
            lineSymbol.Width = 2;

            _lineSymbol = lineSymbol;
        }

        void mapCtrl_OnMouseMove(object sender, IMapControlEvents2_OnMouseMoveEvent e)
        {
            try
            {

                if (_isStarted)
                {
                    if (_pointClt.PointCount == 0)
                    {
                        return;
                    }

                    if (_pointClt.PointCount >= 1)
                    {
                        IPoint fromPt = _pointClt.get_Point(_pointClt.PointCount - 1);
                        IPoint toPt = new PointClass();
                        toPt.PutCoords(e.mapX, e.mapY);
                        if (_tempLine == null)
                        {
                            _tempLine = new PolylineClass();
                        }
                        else
                        {
                            GISCommon.Tools.Drawing.ExitDrawPolyline(_mapCtrl, _tempLine);
                        }
                        _tempLine.FromPoint = fromPt;
                        _tempLine.ToPoint = toPt;
                        //计算临时距离
                        if (_mapCtrl.CurrentTool == null)
                        {
                            _tempDistance = _totalDistance + CalculateDistance(fromPt, toPt);
                        }
                        else
                        {
                            _tempDistance = _totalDistance;
                        }
                        ////画距离
                        //string txt = "当前距离" + _tempDistance.ToString("000,000") + "米";
                        //if (toPt == null)
                        //{
                        //    toPt = _pointClt.get_Point(_pointClt.PointCount - 1);
                        //    DrawText(toPt, txt);
                        //} 
                        if(_canMoveRefresh)
                            _mapCtrl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewForeground, null, null);

                        //Draw();
                    }
                }
            }
            catch (Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用出错", ex);
            }
        }

        private double CalculateDistance(ESRI.ArcGIS.Geometry.IPoint pt1, ESRI.ArcGIS.Geometry.IPoint pt2)
        {
            try
            {
                IMap pMap = _mapCtrl.ActiveView.FocusMap;
                double distance = 0;
                if (pMap != null)
                {
                    distance = pMap.ComputeDistance(pt1, pt2);
                }
                else
                {
                    //计算失败
                    Console.WriteLine("当前视图为空！");
                }

                return distance * 28.2 * 3600;
            }
            catch (Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用CalculateDistance方法出错，", ex);
                return 0;
            }
        }

        void mapCtrl_OnMouseUp(object sender, IMapControlEvents2_OnMouseUpEvent e)
        {
            try
            {
                if (_mapCtrl.MousePointer != esriControlsMousePointer.esriPointerPencil)
                {
                    return;
                }
                if (_mapCtrl.CurrentTool != null)
                {
                    return;
                }
                if (_isStarted)
                {
                    IPoint pt = new PointClass();
                    pt.PutCoords(e.mapX, e.mapY);

                    IPoint fpt = null;
                    if (_pointClt.PointCount > 0)
                    {
                        fpt = _pointClt.get_Point(_pointClt.PointCount - 1);
                    }
                    //计算距离
                    _totalDistance += CalculateDistance(fpt, pt);

                    object obj = System.Reflection.Missing.Value;
                    _pointClt.AddPoint(pt, ref obj, ref obj);

                    _tempLine = null;
                    _mapCtrl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewForeground, null, null);

                    //Draw();
                }
            }
            catch (Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用出错", ex);
            }
        }
        private void DrawText(ESRI.ArcGIS.Geometry.IPoint pPoint, string Text)
        {
            try
            {
                //ITextElement pTextElement = new TextElementClass();
                //pTextElement.Text = Text;
                //IElement pElement = (IElement)pTextElement;
                //pElement.Geometry = pPoint;
                //_mapCtrl.ActiveView.GraphicsContainer.DeleteAllElements();
                //_mapCtrl.ActiveView.GraphicsContainer.AddElement(pElement, 0);
                GISCommon.Tools.Drawing.DrawText(_mapCtrl, pPoint, Text, 10);
                
                //_mapCtrl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);
            }
            catch (Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用DrawText出错！", ex);
            }
        }
        void mapCtrl_OnDoubleClick(object sender, IMapControlEvents2_OnDoubleClickEvent e)
        {
            try
            {
                if (_isStarted)
                {
                    //显示结果信息
                    System.Windows.Forms.MessageBox.Show("量算长度结果：" + 
                        _totalDistance.ToString("000,000") + "(米)");
                    StopMeasure();
                    _tempDistance = 0;
                    _totalDistance = 0;
                    //_mapCtrl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewForeground, null, null);
                    GISCommon.Tools.Drawing.ExitDrawPolyline();
                }
            }
            catch (Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用出错", ex);
            }
        }

        /// <summary>
        /// 描述：开始调用量测功能

        /// </summary>
        /// <returns></returns>
        public bool StartMeasure()
        {
            try
            {
                _isStarted = true;
                //清理MapControl的Tool
                _mapCtrl.CurrentTool = null;
                //改变鼠标形状
                _mapCtrl.MousePointer = esriControlsMousePointer.esriPointerPencil;
                return true;
            }
            catch (Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用StartMeasure出错！", ex);
                return false;
            }
        }

        /// <summary>
        /// 描述：结束调用量测

        /// </summary>
        /// <returns></returns>
        public bool StopMeasure()
        {
            try
            {
                if (!_isStarted) return false;

                //清空所有点
                _pointClt.RemovePoints(0, _pointClt.PointCount);
                _tempLine = null;
                _mapCtrl.ActiveView.PartialRefresh(ESRI.ArcGIS.Carto.esriViewDrawPhase.esriViewForeground,
                    null, null);
                _isStarted = false;
                //改变鼠标形状
                _mapCtrl.MousePointer = esriControlsMousePointer.esriPointerDefault;
                return true;
            }
            catch (Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用StopMeasure出错！", ex);
                return false;
            }
        }

        #endregion
    }
}
